package com.mrjy.maintain.bo;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.mrjy.common.entity.DistributorInfo;
import com.mrjy.common.entity.DistributorTeamInfo;
import com.mrjy.common.entity.ServiceStationInfo;
import com.mrjy.common.entity.TeacherInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserStationCallingRecordRel;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.RegexUtil;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.common.util.UpdateDisableFlagUtil;
import com.mrjy.maintain.dao.IServiceStationInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.dao.IUserStationCallingRecordRelDao;
import com.mrjy.maintain.dto.ServerStationDTO;
import com.mrjy.maintain.dto.ServiceStationParamDTO;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.maintain.util.SharingProportionEnum;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IDistributorTeamInfoDao;
import com.mrjy.share.dto.DistributorInfoDTO;
import com.mrjy.wechat.conts.WxConsts;


@Service("serviceStationInfoBo")
public class ServiceStationInfoBo implements IServiceStationInfoBo {
	
	private Logger LOGGER = LoggerFactory.getLogger(ServiceStationInfoBo.class);
	
	@Resource
	private IServiceStationInfoDao serviceStationInfoDao;
	
	@Resource
	private IUserInfoDao userInfoDao;
	
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	
	@Resource
	private IDistributorTeamInfoDao distributorTeamInfoDao;
	
	@Resource
	private  IUserMemberInfoDao userMemberInfoDao;
	
	@Resource
	private ITeacherInfoDao teacherInfoDao;
	
	@Resource
	private IUserStationCallingRecordRelDao userStationCallingRecordRelDao ;

	@Override
	public List<ServiceStationInfo> serviceStationAllList() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object queryPageServiceStationInfo(
			ServiceStationInfo serviceStationInfo,HttpSession session) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		int count = serviceStationInfoDao.countStation(serviceStationInfo);
		if (count>0) {
			List<ServiceStationInfo> list = serviceStationInfoDao.queryPageStation(serviceStationInfo);
			for (ServiceStationInfo stationInfo : list) {
				if (StringUtils.isNotBlank(stationInfo.getAdminPasswordSrc())) {
					map.put("hasPwd", 0);   //有密码
					stationInfo.setAdminPasswordSrc("");
				}else {
					map.put("hasPwd", 1);  //无密码
				}
			}
			map.put("err_code", 200);
			map.put("err_msg", "查询成功,有数据");
			map.put("total",count);
			map.put("rows", list);
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "查询成功,无数据");
			map.put("total",count);
			map.put("rows", null);
		}
		return map;
	}

	@Override
	public Object queryServiceStationListNoPage(
			ServiceStationInfo serviceStationInfo) {
		List<ServiceStationInfo> list = serviceStationInfoDao.queryPageStation(serviceStationInfo);
		return list;
	}

	@Override
	public String serviceStationValidate(ServiceStationInfo serviceStationInfo,String stid){
		List<ServiceStationInfo> serviceStationInfos = serviceStationInfoDao.queryStationInfo(serviceStationInfo);
		if (serviceStationInfos!=null && serviceStationInfos.size()>0) {
			for (ServiceStationInfo s : serviceStationInfos) {
				if (s.getId().toString().equals(stid)) {
					return "ok";
				}
			}
			return "error";
		}else {
			return "ok";
		}
	}
	
	@Override
	public Object txInsert(ServiceStationInfo serviceStationInfo,HttpSession session) {
		Map<String,Object> map = new HashMap<>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getStationName())) {
			map.put("err_code", 401);
			map.put("err_msg", "服务站名称不能为空");
			return map;
		}
		if (serviceStationInfo.getStationName().length()>16) {
			map.put("err_code", 402);
			map.put("err_msg", "服务站名称过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isNotBlank(serviceStationInfo.getStationMobilePhone()) && 
				!RegexUtil.checkMobile(serviceStationInfo.getStationMobilePhone())) {
			map.put("err_code", 403);
			map.put("err_msg", "手机号格式不正确");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getAdminLoginCode())) {
			map.put("err_code", 413);
			map.put("err_msg", "管理员账号不能为空");
			return map;
		}
		/*if (StringUtils.isBlank(serviceStationInfo.getBankCard())) {
			map.put("err_code", 404);
			map.put("err_msg", "银行卡号不能为空");
			return map;
		}*/
		if (StringUtils.isBlank(serviceStationInfo.getProvince())) {
			map.put("err_code", 405);
			map.put("err_msg", "省份不能为空");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getCity())) {
			map.put("err_code", 406);
			map.put("err_msg", "城市不能为空");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getCounty())) {
			map.put("err_code", 407);
			map.put("err_msg", "区/县不能为空");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getStreet())) {
			map.put("err_code", 408);
			map.put("err_msg", "详细地址不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(serviceStationInfo.getStreet()) && 
				serviceStationInfo.getStreet().length()>30) {
			map.put("err_code", 409);
			map.put("err_msg", "详细地址不能超过30个字符");
			return map;
		}
		if (StringUtils.isNotBlank(serviceStationInfo.getStationDesc()) && 
				serviceStationInfo.getStationDesc().length()>240) {
			map.put("err_code", 410);
			map.put("err_msg", "服务站简介不能超过240个字符");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getSignTimeString())) {
			map.put("err_code", 411);
			map.put("err_msg", "合同签订时间不能为空");
			return map;
		}
		if (serviceStationInfo.getContractTime() == null || serviceStationInfo.getContractTime() <= 0) {
			map.put("err_code", 412);
			map.put("err_msg", "请正确填写合同年限");
			return map;
		}
		if (serviceStationInfo.getSharingProportion() == null) {
			map.put("err_code", 413);
			map.put("err_msg", "分成比例不能为空");
			return map;
		}
		try {
			serviceStationInfo.setRegisterDate(new Date().getTime());
			serviceStationInfo.setDisableFlag(0);

			ServiceStationInfo stationInfo = serviceStationInfoDao.queryByMobliePhone(serviceStationInfo.getStationMobilePhone());
			if (stationInfo!=null) {
				map.put("err_code", 205);    
				map.put("err_msg", "该手机已注册成为服务站，请换个手机号码试试");
				return map;
			}
			UserInfo existInfo = userInfoDao.queryByMobilePhone(serviceStationInfo.getStationMobilePhone());
			if(existInfo != null && existInfo.getRoleId() != RoleInfoEnum.STUDENT.getRoleId() 
					&& existInfo.getRoleId().intValue() != RoleInfoEnum.TEACHER.getRoleId()
					&& existInfo.getRoleId().intValue() != RoleInfoEnum.SCHOOL_ADMIN.getRoleId()){//不是普通用户和讲师,学校
				map.put("err_code", 204);
				map.put("err_msg", "该手机已经被其他角色（非普通用户和讲师）使用，请换个手机号码试试");
				return map;
			}
			//已注册为讲师或普通用户, 但user_info中的记录无密码,则必须输入新密码
			if (existInfo != null && existInfo.getPassword() == null) {
				if (StringUtils.isBlank(serviceStationInfo.getAdminPasswordSrc())) {
					map.put("err_code", 414);
					map.put("err_msg", "密码不能为空");
					return map;
				}
				if (!RegexUtil.checkPwd(serviceStationInfo.getAdminPasswordSrc())) {
					map.put("err_code", 415);
					map.put("err_msg", "密码必须为6-12位,英文和数字的组合");
					return map;
				}
				
			}
			UserInfo loginInfo = userInfoDao.queryByLoginCode(serviceStationInfo.getAdminLoginCode());
			if(loginInfo != null){
				if(existInfo != null && loginInfo.getId().intValue() == existInfo.getId().intValue()){
					//本身自己
				}else{
					//登录账号已被使用
					map.put("err_code", 416);
					map.put("err_msg", "该管理账号已被使用，请重新输入");
					return map;
				}
			}
			
			//设置分成比例
			serviceStationInfo.setSharingProportion(serviceStationInfo.getSharingProportion());
			//处理签订时间和截止有效期
			SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
			try {
				Date d = sdf.parse(serviceStationInfo.getSignTimeString());
				serviceStationInfo.setSignTime(new Timestamp(d.getTime())); //设置签订时间
				//服务站有效期(合同时限)
				serviceStationInfo.setDeadlineTime(new Timestamp(DateUtil.dateTimeAddYears(d.getTime(), serviceStationInfo.getContractTime())));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			serviceStationInfo.setCallingNum(0);//服务站访问次数，默认为0
			int count = serviceStationInfoDao.insert(serviceStationInfo);
			if(count == 1){
				Integer userId = 0;
				int row = 0 ;
				//设置服务站推广码
				String staionRecommendCode = "";
				//20170919 新需求：原本是讲师，又成为服务站，根据现有需求，则用户表修改成role_id = 8（服务站），然后在teacher_info表保存讲师的记录
				//20180111 学校生成服务站的话，则roleId = 11 变成roleId = 13
				if(existInfo != null ){//由于上面做了限制，不为null则为role_id=4 或者role_id=2 (普通用户或讲师),或者学校
					userId = existInfo.getId();
					if(StringUtils.isBlank(existInfo.getRecommendCode())){
						staionRecommendCode = userInfoDao.generateRecommendCodeOne(8);
					}else{
						staionRecommendCode = existInfo.getRecommendCode();
					}
					
					if(existInfo.getRoleId().intValue() == RoleInfoEnum.SCHOOL_ADMIN.getRoleId()){//学校，则升级为13学校和服务站管理员
						existInfo.setRoleId(RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId());
					}else{
						existInfo.setRoleId(RoleInfoEnum.SERVICE_ADMIN.getRoleId());
					}
					
					existInfo.setUserName(serviceStationInfo.getStationName());
					existInfo.setStationId(serviceStationInfo.getId());
					existInfo.setLoginCode(serviceStationInfo.getAdminLoginCode());//管理员账号
					if(existInfo.getPassword() == null) {
						existInfo.setPassword(existInfo.getPassword());
					}
					existInfo.setRecommendCode(staionRecommendCode);
					existInfo.setBankCard(serviceStationInfo.getBankCard());
					existInfo.setProvince(serviceStationInfo.getProvince());
					existInfo.setCity(serviceStationInfo.getCity());
					existInfo.setCounty(serviceStationInfo.getCounty());
					existInfo.setStreet(serviceStationInfo.getStreet());
					row = userInfoDao.updateById(existInfo);
				}else{
					staionRecommendCode = userInfoDao.generateRecommendCodeOne(8);
					
					UserInfo info = new UserInfo();
					info.setUserName(serviceStationInfo.getStationName());
					info.setLoginCode(serviceStationInfo.getAdminLoginCode());//管理员账号
					info.setRecommendCode(staionRecommendCode);
					info.setRoleId(RoleInfoEnum.SERVICE_ADMIN.getRoleId());
					info.setStationId(serviceStationInfo.getId());
					if(StringUtils.isNotBlank(serviceStationInfo.getAdminPasswordSrc())){
						info.setPassword(MD5Encrypt.encryptByMD5(serviceStationInfo.getAdminPasswordSrc()));
					}
					info.setMobilePhone(serviceStationInfo.getStationMobilePhone());
					info.setBankCard(serviceStationInfo.getBankCard());
					info.setProvince(serviceStationInfo.getProvince());
					info.setCity(serviceStationInfo.getCity());
					info.setCounty(serviceStationInfo.getCounty());
					info.setStreet(serviceStationInfo.getStreet());
					if (StringUtils.isNotBlank(serviceStationInfo.getStationTelPhone())) {
						info.setPhone(serviceStationInfo.getStationTelPhone());
					}
					info.setRegisterDate(new Date().getTime());
					info.setDisableFlag(0);
					row = userInfoDao.insert(info);//新增一条
					
					userId = info.getId();
				}
				
				
				if(row == 1){
					//更新推广链接
					serviceStationInfo.setPromoteUrl(WxConsts.PUBLIC_DOMAIN + "/index.html?para="+ staionRecommendCode);
					serviceStationInfoDao.updateById(serviceStationInfo);
					
					//新增服务站推广者
					DistributorInfo dInfo = new DistributorInfo();
					dInfo.setUserId(userId);
					dInfo.setDistributorName(serviceStationInfo.getStationName());
					dInfo.setMobilePhone(serviceStationInfo.getStationMobilePhone());
					dInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
					dInfo.setShareCode(staionRecommendCode);
					dInfo.setDistributorType(SharingProportionEnum.SERVICE_STATION.getDistributorType());
					dInfo.setSharingProportion(serviceStationInfo.getSharingProportion());//分成比例
					dInfo.setDisabledFlag(0);
					dInfo.setProvince(serviceStationInfo.getProvince());
					dInfo.setCity(serviceStationInfo.getCity());
					dInfo.setTown(serviceStationInfo.getCounty());
					dInfo.setUpgradeTime(serviceStationInfo.getSignTime());
					dInfo.setDeadlineTime(serviceStationInfo.getDeadlineTime());
					
					distributorInfoDao.insert(dInfo); 
				}
				
				map.put("err_code", 200);
				map.put("err_msg", "添加成功");
				return map;
			}else{
				map.put("err_code", 500);
				map.put("err_msg", "添加失败");
				return map;
			}
		} catch (Exception e) {
			LOGGER.debug("[服务站插入失败]："+e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("err_code", 500);
			map.put("err_msg", "添加失败");
			return map;
		}
	}

	@Override
	public ServiceStationInfo queryById(int id) {
		return serviceStationInfoDao.queryById(id);
	}

	@Override
	public Object txUpdateById(ServiceStationInfo serviceStationInfo,HttpSession session) {
		Map<String,Object> map = new HashMap<String,Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getStationName())) {
			map.put("err_code", 401);
			map.put("err_msg", "服务站名称不能为空");
			return map;
		}
		if (serviceStationInfo.getStationName().length()>16) {
			map.put("err_code", 402);
			map.put("err_msg", "服务站名称过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isNotBlank(serviceStationInfo.getStationMobilePhone()) && 
				!RegexUtil.checkMobile(serviceStationInfo.getStationMobilePhone())) {
			map.put("err_code", 403);
			map.put("err_msg", "手机号格式不正确");
			return map;
		}
		/*if (StringUtils.isBlank(serviceStationInfo.getBankCard())) {
			map.put("err_code", 404);
			map.put("err_msg", "银行卡号不能为空");
			return map;
		}*/
		if (StringUtils.isNotBlank(serviceStationInfo.getAdminPasswordSrc()) 
				&& !RegexUtil.checkPwd(serviceStationInfo.getAdminPasswordSrc())) {
			map.put("err_code", 415);
			map.put("err_msg", "密码必须为6-12位,英文和数字的组合");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getProvince())) {
			map.put("err_code", 405);
			map.put("err_msg", "省份不能为空");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getCity())) {
			map.put("err_code", 406);
			map.put("err_msg", "城市不能为空");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getCounty())) {
			map.put("err_code", 407);
			map.put("err_msg", "区/县不能为空");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getStreet())) {
			map.put("err_code", 408);
			map.put("err_msg", "详细地址不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(serviceStationInfo.getStreet()) && 
				serviceStationInfo.getStreet().length()>30) {
			map.put("err_code", 409);
			map.put("err_msg", "详细地址不能超过30个字符");
			return map;
		}
		if (StringUtils.isNotBlank(serviceStationInfo.getStationDesc()) && 
				serviceStationInfo.getStationDesc().length()>240) {
			map.put("err_code", 410);
			map.put("err_msg", "服务站简介不能超过240个字符");
			return map;
		}
		if (StringUtils.isBlank(serviceStationInfo.getSignTimeString())) {
			map.put("err_code", 411);
			map.put("err_msg", "合同签订时间不能为空");
			return map;
		}
		if (serviceStationInfo.getContractTime() == null || serviceStationInfo.getContractTime() <= 0) {
			map.put("err_code", 412);
			map.put("err_msg", "请正确填写合同年限");
			return map;
		}
		if (serviceStationInfo.getSharingProportion() == null) {
			map.put("err_code", 413);
			map.put("err_msg", "分成比例不能为空");
			return map;
		}
		int count = 0;
		Boolean isNewNum = false ;
		ServiceStationInfo servicStation = serviceStationInfoDao.queryById(serviceStationInfo.getId());
		UserInfo existInfo = userInfoDao.queryByMobilePhone(serviceStationInfo.getStationMobilePhone());
		if(servicStation != null && StringUtils.isNotBlank(servicStation.getStationMobilePhone())
			&& !servicStation.getStationMobilePhone().equals(serviceStationInfo.getStationMobilePhone())){
			
			ServiceStationInfo stationInfo = serviceStationInfoDao.queryByMobliePhone(serviceStationInfo.getStationMobilePhone());
			if (stationInfo!=null) {
				map.put("err_code", 205);
				map.put("err_msg", "该手机已注册成为服务站，请换个手机号码试试");
				return map;
			}
			
			if(existInfo != null ){//
				map.put("err_code", 202);
				map.put("err_msg", "该手机已被使用，请换个手机号码试试");
				return map;
			}else{
				isNewNum = true ;
			}
		}
		UserInfo loginInfo = userInfoDao.queryByLoginCode(serviceStationInfo.getAdminLoginCode());
		if(loginInfo != null){
			if(existInfo != null && loginInfo.getId().intValue() == existInfo.getId().intValue()){
				//本身自己
			}else{
				//登录账号已被使用
				map.put("err_code", 415);
				map.put("err_msg", "该管理账号已被使用，请重新输入");
				return map;
			}
		}
		
		//处理签订时间和截止有效期
		boolean updateFlag = false;
		SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
		try {
			Date d = sdf.parse(serviceStationInfo.getSignTimeString());
			serviceStationInfo.setSignTime(new Timestamp(d.getTime()));
			//服务站有效期(合同时限)
			serviceStationInfo.setDeadlineTime(new Timestamp(DateUtil.dateTimeAddYears(d.getTime(), serviceStationInfo.getContractTime())));
			updateFlag = true;
		} catch (ParseException e) {
			e.printStackTrace();
			map.put("err_code",500);
			map.put("err_msg", "更新失败");
			return map;
		}
		
		count = serviceStationInfoDao.updateById(serviceStationInfo);
		if(count == 1){
			//更新管理员信息
			UserInfo info = userInfoDao.queryByStationIdForBack(serviceStationInfo.getId()); 
			if(info != null){
				
				info.setLoginCode(serviceStationInfo.getAdminLoginCode());
				if (StringUtils.isNotBlank(serviceStationInfo.getAdminPasswordSrc())) {
					info.setPassword(MD5Encrypt.encryptByMD5(serviceStationInfo.getAdminPasswordSrc()));
				}
				info.setUserName(serviceStationInfo.getStationName());
				info.setMobilePhone(serviceStationInfo.getStationMobilePhone());
				if (StringUtils.isNotBlank(serviceStationInfo.getStationTelPhone())) {
					info.setPhone(serviceStationInfo.getStationTelPhone());
				}
				info.setProvince(serviceStationInfo.getProvince());
				info.setCity(serviceStationInfo.getCity());
				info.setCounty(serviceStationInfo.getCounty());
				info.setStreet(serviceStationInfo.getStreet());
				info.setBankCard(serviceStationInfo.getBankCard());
				userInfoDao.updateById(info);
				
				//以前手机被新手机修改： 则原手机生成新的记录
				if(isNewNum){
					
					String openId = info.getWeixinOpenid() ; 
					String unionId = info.getWeixinUnionid();
					//把之前的数据中的openId清除
					info.setWeixinOpenid(null);
					info.setWeixinUnionid(null);
					int row = userInfoDao.updateOpenIdById(info);
					if(row ==1){
						UserInfo ui = new UserInfo();
						ui.setWeixinOpenid(openId);
						ui.setWeixinUnionid(unionId);
						ui.setHeadImgUrl(info.getHeadImgUrl());
						ui.setMobilePhone(servicStation.getStationMobilePhone());
						ui.setRegisterDate(info.getRegisterDate());
						ui.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
						ui.setEmail(info.getEmail());
						ui.setSex(info.getSex());
						ui.setUserDesc(info.getUserDesc());
						ui.setDisableFlag(0);
						ui.setIdCard(info.getBankCard());
						
						Map<String , Object> paramMap = new HashMap<String , Object>();
						paramMap.put("num", 8);
						paramMap.put("count", 1);
						ui.setRecommendCode(userInfoDao.generateRecommendCode(paramMap));
						int num = userInfoDao.insert(ui);
						//添加推广者
						if(num == 1){
							DistributorInfo disInfo = new DistributorInfo();
							disInfo.setUserId(ui.getId());
							disInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
							disInfo.setShareCode(ui.getRecommendCode());
							disInfo.setDistributorType("0");
							disInfo.setSharingProportion(serviceStationInfo.getSharingProportion());
							disInfo.setDisabledFlag(0);
							distributorInfoDao.insert(disInfo);
						}
						
					}
					
				}
				
				if(updateFlag){
					//更新推广者表的有效期
					Map<String,Object> paramMap = new HashMap<String,Object>();
					paramMap.put("userId", info.getId());
					paramMap.put("disabledFlag", 0);
					paramMap.put("distributorTypes", new String[]{"6"});
					List<DistributorInfoDTO> dInfoList = distributorInfoDao.queryByMap(paramMap);
					if(dInfoList != null && dInfoList.size() > 0){
						DistributorInfo dInfo = dInfoList.get(0);
						dInfo.setDistributorName(info.getUserName());
						dInfo.setMobilePhone(info.getMobilePhone());
						dInfo.setDeadlineTime(serviceStationInfo.getDeadlineTime());
						dInfo.setUpgradeTime(serviceStationInfo.getSignTime());
						dInfo.setSharingProportion(serviceStationInfo.getSharingProportion());
						distributorInfoDao.updateById(dInfo);
					}
				}
				map.put("err_code",200);
				map.put("err_msg", "更新成功");
			}else{
				//过期后重新绑定操作,因为stationId被清空了，所以根据stationId去用户表查询是查不到记录的
				if(existInfo != null){
					existInfo.setLoginCode(serviceStationInfo.getAdminLoginCode());
					if (StringUtils.isNotBlank(serviceStationInfo.getAdminPasswordSrc())) {
						existInfo.setPassword(MD5Encrypt.encryptByMD5(serviceStationInfo.getAdminPasswordSrc()));
					}
					existInfo.setUserName(serviceStationInfo.getStationName());
					existInfo.setMobilePhone(serviceStationInfo.getStationMobilePhone());
					if (StringUtils.isNotBlank(serviceStationInfo.getStationTelPhone())) {
						existInfo.setPhone(serviceStationInfo.getStationTelPhone());
					}
					existInfo.setProvince(serviceStationInfo.getProvince());
					existInfo.setCity(serviceStationInfo.getCity());
					existInfo.setCounty(serviceStationInfo.getCounty());
					existInfo.setStreet(serviceStationInfo.getStreet());
					existInfo.setBankCard(serviceStationInfo.getBankCard());
					existInfo.setStationId(serviceStationInfo.getId());
					if(existInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId()
							|| existInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId()){
						//不修改
					}else if(existInfo.getRoleId().intValue() == RoleInfoEnum.TEACHER.getRoleId()
							|| existInfo.getRoleId().intValue() == RoleInfoEnum.STUDENT.getRoleId()){
						existInfo.setRoleId(RoleInfoEnum.SERVICE_ADMIN.getRoleId()) ;
					}else if(existInfo.getRoleId().intValue() == RoleInfoEnum.SCHOOL_ADMIN.getRoleId()){
						existInfo.setRoleId(RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId());
					}
					
					int row = userInfoDao.updateById(existInfo);
					if(row == 1){
						//更新推广者表
						Map<String,Object> paramMap = new HashMap<String,Object>();
						paramMap.put("userId", existInfo.getId());
						paramMap.put("disabledFlag", 0);
						paramMap.put("distributorTypes", new String[]{"6"});
						List<DistributorInfoDTO> dInfoList = distributorInfoDao.queryByMap(paramMap);
						if(dInfoList != null && dInfoList.size() > 0){
							DistributorInfo dInfo = dInfoList.get(0);
							dInfo.setDistributorName(existInfo.getUserName());
							dInfo.setMobilePhone(existInfo.getMobilePhone());
							dInfo.setDeadlineTime(serviceStationInfo.getDeadlineTime());
							dInfo.setUpgradeTime(serviceStationInfo.getSignTime());
							dInfo.setSharingProportion(serviceStationInfo.getSharingProportion());
							dInfo.setDisabledFlag(0);
							distributorInfoDao.updateById(dInfo);
						}
					}
				}else{
					UserInfo ui = new UserInfo();
					ui.setLoginCode(serviceStationInfo.getAdminLoginCode());
					if (StringUtils.isNotBlank(serviceStationInfo.getAdminPasswordSrc())) {
						ui.setPassword(MD5Encrypt.encryptByMD5(serviceStationInfo.getAdminPasswordSrc()));
					}
					ui.setUserName(serviceStationInfo.getStationName());
					ui.setMobilePhone(serviceStationInfo.getStationMobilePhone());
					if (StringUtils.isNotBlank(serviceStationInfo.getStationTelPhone())) {
						ui.setPhone(serviceStationInfo.getStationTelPhone());
					}
					ui.setProvince(serviceStationInfo.getProvince());
					ui.setCity(serviceStationInfo.getCity());
					ui.setCounty(serviceStationInfo.getCounty());
					ui.setStreet(serviceStationInfo.getStreet());
					ui.setBankCard(serviceStationInfo.getBankCard());
					Map<String , Object> paramMap = new HashMap<String , Object>();
					paramMap.put("num", 8);
					paramMap.put("count", 1);
					ui.setRecommendCode(userInfoDao.generateRecommendCode(paramMap));
					int num = userInfoDao.insert(ui);
					//添加推广者
					if(num == 1){
						DistributorInfo disInfo = new DistributorInfo();
						disInfo.setUserId(ui.getId());
						disInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
						disInfo.setShareCode(ui.getRecommendCode());
						disInfo.setDistributorType("0");
						disInfo.setSharingProportion(serviceStationInfo.getSharingProportion());
						disInfo.setDisabledFlag(0);
						distributorInfoDao.insert(disInfo);
					}
				}
				map.put("err_code",200);
				map.put("err_msg", "更新成功");
			}
		}else{
			map.put("err_code",500);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public int deleteByIds(int[] ids) {
		try {
			return serviceStationInfoDao.deleteByIds(ids);
		} catch (DataAccessException e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public Object txUpdateDisableFlag(ServiceStationInfo serviceStationInfo,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (serviceStationInfo.getIds()==null||serviceStationInfo.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		int row = serviceStationInfoDao.updateDisableFlag(serviceStationInfo);
		if(row > 0){
			for(Integer stationId : serviceStationInfo.getIds()){
				//禁用服务站的同时, 禁用该服务站管理员, 如果该服务站之前是由普通用户或老师升级而来, 则要恢复以前的记录
				int userId = 0;
				ServiceStationInfo info = serviceStationInfoDao.queryById(stationId);
				//通过手机号码去查询用户信息，有可能是roleId=8，或者2或者4的；
				
				List<UserInfo> list = userInfoDao.queryByMobilePhoneIgnoreDisable(info.getStationMobilePhone());
				if (list != null && list.size() > 0 ) {
					UserInfo ui = list.get(0);
					userId = ui.getId();
					//如果启用，则直接修改成roleid为8，并设置 stationid
					if(serviceStationInfo.getDisableFlag().intValue() == 0){//启用时
						ui.setDisableFlag(serviceStationInfo.getDisableFlag());
						ui.setRoleId(RoleInfoEnum.SERVICE_ADMIN.getRoleId());
						ui.setStationId(stationId);
						userInfoDao.updateById(ui);
					}else if(serviceStationInfo.getDisableFlag().intValue() == 1){ // 禁用
						//如果禁用，去讲师表查询，有则修改为roleid=2，没有就修改成4 ，设置stationid为null
						TeacherInfo vo = new TeacherInfo();
						vo.setUserId(ui.getId());
						vo.setDisableFlag(0);
						TeacherInfo ti = teacherInfoDao.queryByUserId(vo);
						if(ti != null ){//是讲师
							ui.setRoleId(RoleInfoEnum.TEACHER.getRoleId());
						}else{//非讲师
							ui.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
						}
						ui.setStationId(null);
						userInfoDao.updateStationIdAndRoleId(ui);
					}
				}else {//不存在的，如果存在数据是错的
					
				}
				
				//操作推广身份信息
				String[] distributorTypes = {"6"};
				UpdateDisableFlagUtil.updateDisableFlagForTeam(distributorTypes,
						userId, serviceStationInfo.getDisableFlag());
			}
			map.put("err_code", 200);
			map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
		return map;
	}

	@Override
	public Map<String, Object> txCheckStationInfoStatusExpired() {
		Map<String,Object> map = new HashMap<String,Object>();
		List<ServiceStationInfo> expireList = serviceStationInfoDao.txCheckStationInfoStatusExpired();
		if(expireList != null && expireList.size() > 0){
			int updateCount = 0;
			TeacherInfo ti = null ;
			UserInfo ui = null ;
			for(ServiceStationInfo info : expireList){
				info.setDisableFlag(1);
				int row = serviceStationInfoDao.updateById(info);
				if(row == 1){
					if(ui == null){
						ui = new UserInfo();
					}
					//查询该服务站之前是否为老师，如果是，则恢复
					TeacherInfo vo = new TeacherInfo();
					vo.setUserId(info.getAdminId());
					vo.setDisableFlag(0);
					ti = teacherInfoDao.queryByUserId(vo);
					if(ti != null){
						ui.setRoleId(RoleInfoEnum.TEACHER.getRoleId());
					}else{
						ui.setRoleId(RoleInfoEnum.STUDENT.getRoleId());
					}
					ui.setId(info.getAdminId());
					ui.setStationId(null);//去掉之前的服务站的id
					userInfoDao.updateStationIdAndRoleId(ui);
					
					//作废合作方的推广者
					String[] distributorTypes = {"6"};
					UpdateDisableFlagUtil.updateDisableFlagForTeam(distributorTypes,
							info.getAdminId(), 1);
					
					updateCount ++;
				}
			}
			map.put("err_code", 0);
			map.put("err_msg", "成功更新了"+ updateCount + "个服务站");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "没有过期的服务站更新");
		}
		return map;
	}

	@Override
	public Object exportExl(ServiceStationInfo serviceStationInfo, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<ServiceStationInfo> data = serviceStationInfoDao.queryPageStation(serviceStationInfo);
		if (data == null || data.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "服务站"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", data, ServiceStationInfo.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public List<DistributorTeamInfo> queryTeamByStationId(ServiceStationInfo serviceStationInfo) {
		return serviceStationInfoDao.queryTeamByStationId(serviceStationInfo);
	}

	@Override
	public Object getTotal(ServiceStationInfo serviceStationInfo) {
		return serviceStationInfoDao.countStation(serviceStationInfo);
	}

	@Override
	public Object checkMobilePhoneExist(ServiceStationInfo serviceStationInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo existInfo = userInfoDao.queryByMobilePhone(serviceStationInfo.getStationMobilePhone());
		if (existInfo != null && existInfo.getPassword()==null) {
			map.put("hasPwd", 1); //无密码
		}else{
			map.put("hasPwd", 0); //有密码
		}
		
		if(existInfo != null && existInfo.getRoleId().intValue() != RoleInfoEnum.STUDENT.getRoleId()
				&& existInfo.getRoleId().intValue() != RoleInfoEnum.TEACHER.getRoleId()
				&& existInfo.getRoleId().intValue() != RoleInfoEnum.SCHOOL_ADMIN.getRoleId()){//不是普通用户和讲师,学校
			map.put("err_code", 400);
			map.put("err_msg", "该手机已经被其他角色（非普通用户、讲师和学校）使用，请换个手机号码试试");
			return map;
		}
		//如果是普通用户或讲师
		if (existInfo !=null) {
			if (existInfo.getPassword() == null) {
				map.put("hasPwd", 1); //无密码
				map.put("err_code", 1);
				map.put("err_msg", "该手机已被非普通用户或讲师或学校注册,您可以自行修改或保留相关信息");
				map.put("userInfo", existInfo);
			}else {
				map.put("hasPwd", 0); //有密码
				map.put("err_code", 1);
				map.put("err_msg", "该手机已被非普通用户或讲师或学校注册,您可以自行修改或保留相关信息");
				existInfo.setPassword(null);
				map.put("userInfo", existInfo);
			}
		}else {
			map.put("err_code", 0);
			map.put("err_msg", "该手机未被注册,可以使用");
		}
		
		
		return map;
	}

	@Override
	public Object queryStationPage(ServiceStationParamDTO dto) {
		List<ServerStationDTO> list = serviceStationInfoDao.queryStationPage(dto) ;
		int total = serviceStationInfoDao.queryCountStationPage(dto) ;
		return ResultUtil.success(list,total);
	}

	@Override
	public Object txAddCallingNumById(Integer id , Integer userId) {
		int row =serviceStationInfoDao.txAddCallingNumById(id);
		if(row > 0){
			UserStationCallingRecordRel rel = new UserStationCallingRecordRel() ;
			rel.setStationId(id);
			rel.setUserId(userId);
			rel.setCreateTime(new Timestamp(System.currentTimeMillis()));
			userStationCallingRecordRelDao.insert(rel);
			return ResultUtil.success();
		}else {
			return ResultUtil.error() ;
		}
	}
}
